#include <stdio.h>
#include "motion9_dll.h"
#include "c_mutex.h"
#include "msg_queue.h"
#include "control.h"

extern STRUCT_CONTROL Ct;
static void exportMsg();

#ifdef WINDOWS_P
#include<Windows.h>
HANDLE hMutexInterface;
CRITICAL_SECTION  _critical;
HANDLE hSemaphore;		//lock 0
HANDLE hSemaphoreRun;		//lock1
#endif

#ifdef LINUX_P
#include <pthread.h>
pthread_mutex_t hMutexCmd;
pthread_mutex_t hMutexService;
#endif


#ifdef WINDOWS_P
DWORD WINAPI message_thread(LPVOID pArg)
{
	while (1){
		C_SLEEP_MS(10);
		exportMsg();
	}
	return 0;
}
#endif

#ifdef LINUX_P
void *message_thread(void *param)
{
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
	pthread_detach(pthread_self());
	while (1){
		C_SLEEP_MS(10);
		exportMsg();
	}
	pthread_exit(0);
}
#endif

void exportMsg()
{
	STRUCT_MS *msg = NULL;
	int len = msqLen();
	if (len >= 1){
		while (msqLen() >= 1){
			msg = msqItem(0);
			if (msg != NULL && Ct.conf.callback_msg != NULL){
				Ct.conf.callback_msg(msg->reason, msg->data);
			}
			msqRemove(1);
			msg = NULL;
		}
	}
}

int mtInterfaceCreat()
{
#ifdef WINDOWS_P
	HANDLE hThread1;
	int ret = 0;
	hSemaphore = CreateSemaphore(NULL, 1, 1, NULL);
	hSemaphoreRun = CreateSemaphore(NULL, 1, 1, NULL);
	hThread1 = CreateThread(NULL, 0, message_thread, &ret, 0, NULL);
#endif
#ifdef LINUX_P
	pthread_mutex_init(&hMutexCmd,NULL);
	pthread_mutex_init(&hMutexService, NULL);
	pthread_t threadid_msg;
	pthread_create(&threadid_msg, NULL, message_thread, NULL);
#endif
	return 0;
}

void mtInterfaceLock(char num,int msecond)
{
#ifdef WINDOWS_P
	if (LOCKER_CMD == num) {
		WaitForSingleObject(hSemaphore, INFINITE);
	}
	else if (LOCKER_SERVICE == num){
		WaitForSingleObject(hSemaphoreRun, msecond);
	}
#endif
#ifdef LINUX_P
	if (LOCKER_CMD == num) {
		pthread_mutex_lock(&hMutexCmd); 
	}
	else if (LOCKER_SERVICE == num){
		//if(pthread_mutex_trylock(&hMutexService) != 0);
		//C_SLEEP_MS(msecond);
		//pthread_mutex_unlock(&hMutexService);
		pthread_mutex_lock(&hMutexService);
	}
#endif
	return;
}

void mtInterfaceUnlock(char num)
{
#ifdef WINDOWS_P
	if (LOCKER_CMD == num) {
		ReleaseSemaphore(hSemaphore, 1, NULL);
	}
	else if (LOCKER_SERVICE == num){
		ReleaseSemaphore(hSemaphoreRun, 1, NULL);
	}
#endif
#ifdef LINUX_P
	if (LOCKER_CMD == num) {
		pthread_mutex_unlock(&hMutexCmd);
	}
	else if (LOCKER_SERVICE == num){
		pthread_mutex_unlock(&hMutexService);
	}
#endif
	return;
}

